package com.example.anwserai.demos.web.service;


import com.example.anwserai.demos.web.entity.DocumentAnalysisResult;
/*import com.example.anwserai.demos.web.util.QwenApiUtilQ4;*/
import com.example.anwserai.demos.web.util.QwenApiUtilQ40317;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

@AllArgsConstructor
@Slf4j
@Service
public class AIServiceImpl{




    public DocumentAnalysisResult extractMainInfo(File file) {
        long start = System.currentTimeMillis();

        System.out.println("需求四，提取重要信息开始---------------------------------------------------------------");

        DocumentAnalysisResult documentAnalysisResult = officialAnalyse(file);
        return documentAnalysisResult;
    }

    /**
     *
     * @param \: 文件路径
     * @return: 需求4指标对对象
     */
    public static DocumentAnalysisResult officialAnalyse(File file) {
        /*String filename = file.getName();
        System.out.println("filename:::"+filename);
        // (1)只能处理.doc和.docx   pdf文件
        String fileType = filename.substring(filename.lastIndexOf("."));*/

        // (2)读取文件
        String text = read(file);
        /*String text = null;*/
        long startTime1 = System.currentTimeMillis();

        /*switch (fileType) {
            case ".docx":
                text = redDocx(file.getAbsolutePath());
                //text = FileUtilQ2.redDocx(filePath);
                break;
            case ".doc":
                text = redDoc(file.getAbsolutePath());
                //text = FileUtilQ3.redDoc(filePath);
                break;
            case ".pdf":
                text = redPDF(file.getAbsolutePath());
                //text = FileUtilQ3.redPDF(filePath);
                break;
        }*/
        if (!StringUtils.hasLength(text)) {
            throw new RuntimeException("解析后结果为空");
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("解析文件所花费时长：" + (endTime1-startTime1) + " 毫秒");
        // (3)请求AI的接口（Qwen）,并返回原response
        long startTime = System.currentTimeMillis();
        String message = QwenApiUtilQ40317.analyzeNotice(text);
        long endTime = System.currentTimeMillis();
        System.out.println("ai解析执行时长：" + (endTime-startTime) + " 毫秒");
        // (4)处理失败，递归提交并等待新任务结果
        if (!StringUtils.hasLength(message)) {
            throw new RuntimeException("提取结果为空");
        }

        // 提取结果为对象
        return QwenApiUtilQ40317.getContent(message,file); // 结果
    }
    public static String read(File file){
        String filename = file.getName();
        System.out.println("filename:::"+filename);
        // (1)只能处理.doc和.docx   pdf文件
        String fileType = filename.substring(filename.lastIndexOf("."));
        String text = null;
        long startTime1 = System.currentTimeMillis();

        switch (fileType) {
            case ".docx":
                text = redDocx(file.getAbsolutePath());
                //text = FileUtilQ2.redDocx(filePath);
                break;
            case ".doc":
                text = redDoc(file.getAbsolutePath());
                //text = FileUtilQ3.redDoc(filePath);
                break;
            case ".pdf":
                text = redPDF(file.getAbsolutePath());
                //text = FileUtilQ3.redPDF(filePath);
                break;
        }
        return text;
    }

    public static String redDoc (String fileName) {
        try (FileInputStream fis = new FileInputStream(fileName);
             HWPFDocument document = new HWPFDocument(fis)) {
            WordExtractor extractor = new WordExtractor(document);
            String text = extractor.getText();
            if (StringUtils.hasLength(text)) {
                return text;
            }
            throw new RuntimeException("DOC读取为空");
        } catch (Exception e) {
            throw new RuntimeException("DOC解析失败");
        }
    }

    public static String redDocx(String fileName) {
        try (FileInputStream fis = new FileInputStream(fileName);
             XWPFDocument document = new XWPFDocument(fis);
             XWPFWordExtractor extractor = new XWPFWordExtractor(document)) {
            String text = extractor.getText();
            if (StringUtils.hasLength(text)) {
                return text;
            }
            throw new RuntimeException("DOCX读取为空");
        } catch (Exception e) {
            throw new RuntimeException("DOCX解析失败");
        }
    }

    public static String redPDF(String fileName) {
        try {
            // 使用 Path 和 InputStream 加载 PDF 文档
            File file = new File(fileName);
            PDDocument document = PDDocument.load(file);

            // 创建 PDFTextStripper 对象
            PDFTextStripper stripper = new PDFTextStripper();

            // 提取文本
            String text = stripper.getText(document);
            // 关闭文档
            document.close();
            if (StringUtils.hasLength(text)) {
                if (fileName.startsWith("关于做好2024年端午期间价格监测工")) {
                    log.info("目标文件解析结果：{}", text);
                }
                return text;
            }
            if (fileName.startsWith("关于做好2024年端午期间价格监测工")) {
                System.out.println("目标文件解析为空");
            }
            throw new RuntimeException("PDF读取为空，可能是图片");
        } catch (Exception e) {
            if (fileName.startsWith("关于做好2024年端午期间价格监测工")) {
                System.out.println("目标文件解析出错");
            }
            throw new RuntimeException("PDF解析失败");
        }
    }

}
